package lib;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import main.ErrorException;
import main.WarningHandler;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import define.Common;
import define.ErrorDefine;
import define.WarningDefine;

public class WorkbookInLib 
{
	private Workbook m_workbook;
	private boolean m_isUseHssf;
	private String m_path;

	public WorkbookInLib(String fileName) throws ErrorException 
	{
		m_path = fileName;
		FileInputStream inputStream = null;
		String extendName = Common.getExtendName(fileName);
		m_isUseHssf = extendName.compareTo("xls") == 0;
		try 
		{
			inputStream = new FileInputStream(m_path);
		} 
		catch (Exception e) 
		{
			throw new ErrorException(ErrorDefine.E_CANT_FIND_EXCEL_ERROR, fileName);
		}
		try 
		{
			if(m_isUseHssf)
			{
				m_workbook = new HSSFWorkbook(inputStream);
			}
			else
			{
				m_workbook = new XSSFWorkbook(inputStream);
			}
		} 
		catch (Exception e) 
		{
			throw new ErrorException(ErrorDefine.E_CANT_OPEN_EXCEL_ERROR, fileName);
		} 
		finally 
		{
			if (inputStream != null) 
			{
				try 
				{
					inputStream.close();
				} 
				catch (Exception e2) 
				{
				}
			}
		}
	}
	
	protected Workbook getRealWorkbook() 
	{
		return m_workbook;
	}
	
	protected boolean isUseHssf()
	{
		return m_isUseHssf;
	}
	
	public int getSheetNumber()
	{
		return m_workbook.getNumberOfSheets();
	}
	
	public SheetInLib getSheet(int index)
	{
		return new SheetInLib(m_workbook.getSheetAt(index), this);
	}
	
	public SheetInLib getSheet(String sheetName)
	{
		Sheet sheet = m_workbook.getSheet(sheetName);
		if(sheet == null)
		{
			return null;
		}
		return new SheetInLib(sheet, this);
	}
	
	public SheetInLib addSheet(String name, int position) throws ErrorException
	{
		Sheet sheet = m_workbook.getSheet(name);
		if(sheet != null)
		{
			m_workbook.removeSheetAt(m_workbook.getSheetIndex(sheet));
			new WarningHandler(WarningDefine.E_SHEET_HAS_EXISTS_WARNING, name, position).showWarning();
		}
		sheet = m_workbook.createSheet(name);
		return new SheetInLib(sheet, this);
	}
	
	protected CellStyle createCellStyle()
	{
		return m_workbook.createCellStyle();
	}
	
	public void write(int position) throws ErrorException
	{
		FileOutputStream fos = null;
		try 
		{
			fos = new FileOutputStream(m_path);
			m_workbook.write(fos);
		} 
		catch(Exception e) 
		{
			throw new ErrorException(ErrorDefine.E_CANT_WRITE_EXCEL_ERROR, m_path, position);
		}
		finally
		{
			if(fos != null)
			{
				try 
				{
					fos.close();
				}
				catch(Exception e2) 
				{
				}
			}
		}
	}
}
